package czk.concrent.juc.countDOwnLatch.practice;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 模仿游戏加载的过程
 * @Author:ChenZhangKun
 * @Date: 2020/8/31 23:54
 */
public class PeaceElite {
    public static void main(String[] args) throws InterruptedException {
        // 创建计数线程,四个人
        CountDownLatch countDownLatch=new CountDownLatch(4);
        ExecutorService executorService = Executors.newFixedThreadPool(4);
        // 创建数组
        String[] players=new String[4];
        // 创建随机数
        Random random=new Random();
        // 创建4个线程
        for (int i = 0; i < 4; i++) {
            int m=i;
            executorService.execute(()->{
                // 加载到100%
                for (int j = 1; j <=100 ; j++) {
                    // 先休息
                    try {
                        Thread.sleep(random.nextInt(100));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    players[m]=j+"%";
                    System.out.print("\r" + Arrays.toString(players));
                }
                countDownLatch.countDown();
            });
        }
        // 主线程等待
        countDownLatch.await();
        System.out.println();
        System.out.println("所有玩家加载完毕，开始游戏");
        executorService.shutdown();
    }
}
